import { Module } from 'vuex';
import { PFUserInfo, SysUser, useAuth } from 'pf-component';
import { cacheUtils } from '@/constants/util/cache-utils';
import { RootModule } from '@/store/index';

type UsersModule = { userInfo: SysUser; pfUserInfo: PFUserInfo; currentTenId: string };
export const users: Module<UsersModule, RootModule> = {
  namespaced: true,
  state: {
    userInfo: cacheUtils.get('userInfo') || {},
    pfUserInfo: cacheUtils.get('pfUserInfo') || {},
    currentTenId: cacheUtils.get('currentTenId') || ''
  },
  mutations: {
    INIT_PFUSERS: (state: UsersModule) => {
      const pfUserInfo = useAuth().getUserInfo();
      cacheUtils.set('pfUserInfo', pfUserInfo);
      state.pfUserInfo = pfUserInfo;
    },
    INIT_USERS: (state: UsersModule, payload: SysUser) => {
      state.userInfo = payload;
      state.currentTenId = payload.tenId;
      cacheUtils.set('userInfo', payload);
      cacheUtils.set('currentTenId', payload.tenId);
    }
  },
  actions: {
    async initPfUsers({ commit }) {
      return useAuth()
        .loadUserByToken2()
        .then(res => {
          if (res) {
            commit('INIT_PFUSERS');
            return true;
          } else {
            return false;
          }
        })
        .catch(err => {
          console.error('loadUserByToken2.....', err);
          return false;
        });
    },
    async initUsers({ commit }, payload: SysUser) {
      commit('INIT_USERS', payload);
      return true;
    }
  }
};
